import router from '@/router';
import $ from 'jquery'
export default{
    state: {
        id:'',
        username:'',
        photo:'',
        token:'',
        isLogin:false,
    },
    getters: {
    },
    mutations: {
        LoginUser(state,user){
            state.id = user.id;
            state.username = user.username;
            state.photo = user.photo;
            state.isLogin = true;
        },
        GetToken(state,token){
            state.token = token;
        },
        Logout(state){
            state.id = '';
            state.username = '';
            state.photo = '';
            state.token = '';
            state.isLogin = false;
        }
    },
    actions: {
        // 登录发第一次请求获取token
        login(context,data){
            $.ajax({
                url:"https://xwjsnakebot.com.cn/api/user/account/token/",
                type:"post",
                data:{
                  username:data.username,
                  password:data.password,
                },
                success(resp){
                    // 放在storage中
                    localStorage.setItem('jwt_token',resp.token)
                    context.commit('GetToken',resp.token);
                    // 登录成功后获取用户信息
                    context.dispatch('getUser','/')
                    // router.push('/');放在这，需要点两下按钮，虽然放在getUser方法后面，但会先执行这行代码
                },
                error(){
                    alert('用户名或密码错误')
                }
            })
        },
        // 获取用户信息
        getUser(context,path){
            // 携带后端处理后的token再次请求从后端获取用户信息
            $.ajax({
                url:"https://xwjsnakebot.com.cn/api/user/account/info/",
                type:"post",
                headers: {
                    Authorization:"Bearer "+context.state.token
                },
                success(resp){
                    context.commit('LoginUser',{...resp})
                    router.push(path);//获取信息就跳转，放在这，就只用点一下按钮
                },
                error(){
                    router.push('/user/account/login/')
                }
            })
        }
    },
    modules: {
    }
}